//
//  NSString+Python.m
//  CommonTools
//
//  Created by caoyuan on 5/24/16.
//  Copyright © 2016 baidu. All rights reserved.
//

#import "NSString+Python.h"

@implementation NSString (Python)
- (NSString* (^)(NSString *))pyAppend {
    return ^(NSString *str) {
        //code
        NSString *subStr;
        if (str) {
            subStr = [NSString stringWithFormat:@"%@%@",self,str];
        }
        return subStr;
    } ;
}



- (NSInteger (^)(NSString *subStr))pyFind {
    return ^(NSString *subStr) {
        
        NSRange range;
        range = [self rangeOfString:subStr];
        if (range.location != NSNotFound) {
            return (NSInteger)range.location;
        }else{
            return (NSInteger)(-1);
        }
    };
}

- (NSString* (^)(NSString *, NSString *))pyReplace {
    return ^(NSString *oldStr, NSString *newStr) {
        //code
        NSString *subStr;
        if (oldStr && newStr) {
            subStr = [self stringByReplacingOccurrencesOfString:oldStr withString:newStr];
            return subStr;
        }
        else
            return self;
    };
}

- (NSString* (^)(NSInteger , NSInteger ))pyRange {
    return ^(NSInteger begin, NSInteger end) {
        //code
        
        if (begin < 0) {
            begin = 0;
        }
        if (end > [self length]) {
            end = [self length];
        }
        
        NSString *subStr;
        NSRange r;
        r.location = begin;
        r.length = end - begin;
        subStr = [self substringWithRange:r];
        return subStr;
        
    };
}

- (NSString *(^)(void))pyReverse {
    return ^(void) {
        //code
        NSString *resStr = [self stringByReversed];
        return resStr;
    };
}

- (NSString *)stringByReversed{
    if (!self) {
        return nil;
    }
    if (self.length == 0) {
        return @"";
    }
    NSUInteger i = 0;
    NSUInteger j = self.length - 1;
    unichar characters[self.length];
    while (i < j) {
        characters[j] = [self characterAtIndex:i];
        characters[i] = [self characterAtIndex:j];
        i ++;
        j --;
    }
    if(i == j)
        characters[i] = [self characterAtIndex:i];
    return [NSString stringWithCharacters:characters length:self.length];
}
@end
